<?php

/**
 * 角色分离处理类
 */
class CharacterDataHandle
{
    private $character_and_time;
    private $count;
    private $roles_for_repalce = [];
    private $role_num = 1;
    public function __construct()
    {
        $this->count = 0;
    }

    public function getCharacterArray()
    {
        return $this->character_and_time;
    }

    public function setCharacterArray(array $_array)
    {
        $array = $this->sortCharacterData($_array);
        if ($this->character_and_time == null) {
            $this->takeDataHandle($array);
        } else {
            $this->takeDataHandleintoHistory($array);
        }
    }

    private function takeDataHandle(array $_array)
    {
        $this->character_and_time = $this->specifiedCharacterData($_array);
        $this->count = count($this->character_and_time);
    }

    private function takeDataHandleintoHistory(array $_array)
    {
        $array = $this->specifiedCharacterData($_array);
        $character_data_length = $this->character_and_time[$this->count - 1]['endTime'];
        foreach ($array as &$value) {
            $value['startTime'] += $character_data_length;
            $value['endTime'] += $character_data_length;
        }
        $this->character_and_time = array_merge($this->character_and_time, $array);
        $this->count = count($this->character_and_time);
    }

    //格式化处理
    private function specifiedCharacterData(array $_array)
    {
        foreach ($_array as &$value) {
            $tmp = explode(";", trim($value));
            $value = [
                "startTime" => round(($tmp[0] + 0)/100, 0),
                "endTime" => round(($tmp[1] + 0)/100, 0),
                "sex" => $tmp[2],
                //"character" => $tmp[3]
                "character" => $this->roleReplace($tmp[3])
            ];
        }
        return $_array;
    }

    private function sortCharacterData(array $_array)
    {
        //自然数排序
        array_multisort($_array, SORT_NATURAL);
        return $_array;
    }

    //角色替换
    private function roleReplace($original_role){
        if(!array_key_exists($original_role, $this->roles_for_repalce)){
            $this->roles_for_repalce[$original_role] = "角色" . $this->role_num++;
        }
        return $this->roles_for_repalce[$original_role];
    }
}
